package com.github.defense.plugin.gray.decision.factory;

import com.github.defense.plugin.gray.decision.GrayDecision;
import com.github.defense.plugin.gray.request.GrayHttpRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 基于Header参数做校验
 *
 * @Author: lettger
 * @Date: 2021/6/8 1:30 下午
 */
@Slf4j
public class HeaderGrayDecisionFactory extends AbstractGrayDecisionFactory<HeaderGrayDecisionFactory.Config> {


    public HeaderGrayDecisionFactory() {
        super(Config.class);
    }


    @Override
    public GrayDecision apply(Config config) {
        return args -> {
            log.debug("Header Config:{}", config);
            GrayHttpRequest request = (GrayHttpRequest) args;
            List<String> values = request.getHeader(config.getName());
            if (CollectionUtils.isEmpty(values)) {
                return false;
            }
            return config.getStrategy().compare(values, config.regexp);
        };
    }

    @Getter
    @Setter
    @ToString
    public static class Config extends AbstractGrayStrategyFactory.Strategy {
        /**
         * 需要校验的Header参数名称
         */
        private String name;
        /**
         * 需要校验Header参数的值,也可以是正则
         */
        private String regexp;
    }
}
